#!/bin/bash

set -e          # exit on error
set -o pipefail # exit on pipeline error
set -u          # treat unset variable as error

. "/minioslib" || exit 1
. "/minios-build.conf" || exit 1

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"

if [ -d "/usr/lib/systemd/system" ]; then
    SYSTEMD_PATH="/usr/lib/systemd"
elif [ -d "/lib/systemd/system" ]; then
    SYSTEMD_PATH="/lib/systemd"
fi

timezone_to_array

if [ "${LOCALE}" != "en_US" ]; then
    DEBCONF_SETTINGS=(
        "keyboard-configuration  keyboard-configuration/layoutcode       string  us,${LAYOUTID}"
        "keyboard-configuration  keyboard-configuration/variant  select  ${LAYOUTDSC}"
        "keyboard-configuration  keyboard-configuration/toggle   select  Alt+Shift"
        "tzdata  tzdata/Zones/${TIMEZONE[0]}     select  ${TIMEZONE[1]}"
        "locales locales/locales_to_be_generated multiselect     ${LOCALE}.UTF-8 UTF-8"
    )
else
    DEBCONF_SETTINGS=(
        "locales locales/locales_to_be_generated multiselect     en_US.UTF-8 UTF-8"
    )
fi

DEBCONF_SETTINGS+=(
    "locales locales/default_environment_locale      select  ${LOCALE}.UTF-8"
    "davfs2 davfs2/suid_file boolean true"
    "console-setup   console-setup/codeset47 select  Guess optimal character set"
    "console-setup   console-setup/charmap47 select  UTF-8"
    "console-setup   console-setup/fontsize-fb47 select  8x16"
    "console-setup   console-setup/fontface47select  Fixed"
    "console-setup   console-setup/fontsize-text47   select  8x16"
    "openssh-server  openssh-server/password-authentication  boolean true"
    "openssh-server  openssh-server/permit-root-login        boolean false"
)

DEBCONF_SETTINGS+=(
    "keyboard-configuration  keyboard-configuration/layout   select  ${LAYOUTDSC}"
)

if [ "${MULTILINGUAL}" = "true" ]; then
    LOCALES_STRING=""
    for ITEM in "${!LOCALES[@]}"; do
        LOCALES_STRING+="${ITEM}.UTF-8 UTF-8, "
    done
    LOCALES_STRING=${LOCALES_STRING%??}
    DEBCONF_SETTINGS+=(
        "locales locales/locales_to_be_generated multiselect ${LOCALES_STRING}"
    )
fi

for SETTING in "${DEBCONF_SETTINGS[@]}"; do
    echo "${SETTING}" | debconf-set-selections -v
done

if ! dpkg -s gpg &>/dev/null; then
    pkg install gpg
fi

curl -k https://minios.dev/debian/minios-linux.asc | gpg --dearmor >/etc/apt/trusted.gpg.d/minios-linux.gpg
>/etc/apt/sources.list.d/minios-linux.list
if [ "${DISTRIBUTION}" = "bookworm" ] || [ "${DISTRIBUTION}" = "sid" ] || [ "${DISTRIBUTION}" = "jammy" ] || [ "${DISTRIBUTION}" = "noble" ] || [ "${DISTRIBUTION}" = "bionic" ]; then
    echo "deb https://minios.dev/debian/ ${DISTRIBUTION} main contrib non-free" >/etc/apt/sources.list.d/minios-linux.list
    echo "#deb-src https://minios.dev/debian/ ${DISTRIBUTION} main contrib non-free" >>/etc/apt/sources.list.d/minios-linux.list
fi
echo "deb https://minios.dev/debian/ generic main contrib non-free" >>/etc/apt/sources.list.d/minios-linux.list
echo "#deb-src https://minios.dev/debian/ generic main contrib non-free" >>/etc/apt/sources.list.d/minios-linux.list
cat <<EOF >/etc/apt/preferences.d/minios-linux
Package: *
Pin: release l=MiniOS Repository
Pin-Priority: 1001
EOF

pkg update && pkg upgrade

ADD_PACKAGES=""
DELETE_PACKAGES=""
REPLACE_PACKAGES=""

# Install packages based on distribution
case "${DISTRIBUTION}" in
"bookworm" | "trixie" | "sid")
    if [ "${KERNEL_BUILD_DKMS}" = "false" ]; then
        DELETE_PACKAGES+=" zfsutils-linux"
    fi
    ;;
"jammy")
    ADD_PACKAGES+=" netplan.io"
    ;;
"noble")
    ADD_PACKAGES+=" netplan.io"
    ;;
*)
    if [ "${DISTRIBUTION_TYPE}" = "ubuntu" ]; then
        ADD_PACKAGES+=" netplan.io"
    fi
    ;;
esac

if [ "${KERNEL_TYPE}" = "none" ]; then
    DELETE_PACKAGES+=" zfsutils-linux"
fi

if [ "${DESKTOP_ENVIRONMENT}" = "flux" ] && [ "${PACKAGE_VARIANT}" = "minimum" ]; then
    DELETE_PACKAGES+=" jq"
    ADD_PACKAGES+=" connman"
else
    ADD_PACKAGES+=" network-manager"
fi

# Check if package variant list file exists
if [ -f "${SCRIPT_DIR}/${PACKAGE_VARIANT}.list" ]; then
    install_packages --add-packages ${ADD_PACKAGES} --delete-packages ${DELETE_PACKAGES} --replace-packages ${REPLACE_PACKAGES}
fi

if [ "${DISTRIBUTION_TYPE}" = "ubuntu" ]; then
    pkg autoremove linux-modules-extra-* linux-firmware
fi

if [ "${DESKTOP_ENVIRONMENT}" = "flux" ] || [ "${PACKAGE_VARIANT}" = "minimum" ] || [ "${DISTRIBUTION}" = "noble" ]; then
    systemctl disable dnsmasq
fi

if [ -f /bin/ping ]; then
    chmod +s /bin/ping
fi

if grep -q docker "${SCRIPT_DIR}/${PACKAGE_VARIANT}.list"; then
    systemctl disable docker.socket
    systemctl disable docker.service
    systemctl disable containerd.service
fi
if grep -q libvirt "${SCRIPT_DIR}/${PACKAGE_VARIANT}.list"; then
    systemctl disable libvirtd
fi
if grep -q open-iscsi "${SCRIPT_DIR}/${PACKAGE_VARIANT}.list"; then
    systemctl disable iscsid
fi
if grep -q nfs-common "${SCRIPT_DIR}/${PACKAGE_VARIANT}.list"; then
    systemctl disable rpcbind
fi

# configuration

(cd /linux-live/scripts/00-core/rootcopy-install && cp --parents -afr * /)

# minios-install setup
if [ ! -d /usr/lib/usev/rules.d ]; then
    mkdir -p /usr/lib/udev/rules.d
fi
cat <<EOF >/usr/lib/udev/rules.d/90-minios-automount.rules
# we don't care about loop* and ram* devices
KERNEL=="[!lr]*", SUBSYSTEM=="block", RUN+="/usr/sbin/minios-automount %r/%k"

EOF
if [ -d /etc/NetworkManager ] && [[ "${DISTRIBUTION}" = "jammy" || "${DISTRIBUTION}" = "noble" || "${DISTRIBUTION_TYPE}" = "ubuntu" ]]; then
    if [ ! -d /etc/netplan/ ]; then
        mkdir -p /etc/netplan/
    fi
    cat <<EOF >/etc/netplan/01-netcfg.yaml
# This file describes the network interfaces available on your system
# For more information, see netplan(5).
# Set and change netplan renderer to NetworkManager GUI tool 
network:
  version: 2
  renderer: NetworkManager

EOF
    cat <<EOF >/etc/NetworkManager/NetworkManager.conf
[main]
rc-manager=resolvconf
plugins=ifupdown,keyfile
dns=dnsmasq
[ifupdown]
managed=false

EOF
fi

if [ -f /etc/systemd/system/multi-user.target.wants/grub-initrd-fallback.service ]; then
    echo "Disable grub-initrd-fallback.service autostart."
    systemctl disable grub-initrd-fallback.service
fi

if grep -q ssh "${SCRIPT_DIR}/${PACKAGE_VARIANT}.list"; then
    echo "Enable ssh.service autostart."
    cat <<EOF >"${SYSTEMD_PATH}/system/ssh-keygen.service"
[Unit]
Description=Generate sshd keys
Before=ssh.service

[Service]
Type=oneshot
ExecStart=-/bin/sh -c 'if ! ls /etc/ssh/ssh_host_* >/dev/null 2>&1; then ssh-keygen -A; fi; if [ ! -d /run/sshd ]; then mkdir -p /run/sshd; fi'
RemainAfterExit=true
StandardOutput=journal

[Install]
WantedBy=multi-user.target
EOF
    systemctl enable ssh-keygen
    systemctl disable ssh
fi

if [ ! -f /usr/share/sudo ]; then
    cat <<EOF >/usr/share/sudo
#!/bin/bash
if [ "\$#" -lt 1 ]; then
   echo "Usage: sudo [command] [arguments]"
   exit 1
fi

if [ "\$UID" = 0 ]; then
   exec "\$@"
fi

echo "Sudo is not installed. Run the command as root or install sudo."
EOF
fi

# configure locales
if [ -f /etc/locale.gen ]; then
    sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen
fi

if [ "${DISTRIBUTION_TYPE}" = "ubuntu" ]; then
    cat >/etc/default/keyboard <<'EOF'
# KEYBOARD CONFIGURATION FILE

# Consult the keyboard(5) manual page.

XKBMODEL="pc105"
XKBLAYOUT="us"
XKBVARIANT=""
XKBOPTIONS=""

BACKSPACE="guess"
EOF
    dpkg-reconfigure -f noninteractive keyboard-configuration
fi

if grep console-setup "${SCRIPT_DIR}/${PACKAGE_VARIANT}.list"; then
    cat >/etc/default/console-setup <<'EOF'
# CONFIGURATION FILE FOR SETUPCON

# Consult the console-setup(5) manual page.

ACTIVE_CONSOLES="/dev/tty[1-6]"

CHARMAP="UTF-8"

CODESET="guess"
FONTFACE="Fixed"
FONTSIZE="8x16"

VIDEOMODE=

# The following is an example how to use a braille font
# FONT='lat9w-08.psf.gz brl-8x8.psf'
EOF
    dpkg-reconfigure -f noninteractive console-setup
fi

if grep -q firewalld "${SCRIPT_DIR}/${PACKAGE_VARIANT}.list"; then
    systemctl disable firewalld
else
    rm -rf /etc/firewalld
fi
if grep -q cockpit "${SCRIPT_DIR}/${PACKAGE_VARIANT}.list"; then
    systemctl disable cockpit.socket
fi

if grep -q laptop-mode-tools "${SCRIPT_DIR}/${PACKAGE_VARIANT}.list"; then
    if [ -f /usr/share/applications/laptop-mode-tools.desktop ]; then
        rm /usr/share/applications/laptop-mode-tools.desktop
    fi
fi

if ! grep -q LANG /etc/default/locale; then
    echo "LANG=\"${LOCALE}.UTF-8\"" >>/etc/default/locale
fi

dpkg-reconfigure -f noninteractive locales

echo root:"${ROOT_PASSWORD}" | chpasswd
cp -f /etc/skel/.bashrc /root/

if wget -O /usr/bin/pacapt https://github.com/icy/pacapt/raw/ng/pacapt 2>/dev/null; then
    chmod 755 /usr/bin/pacapt
    ln -sv /usr/bin/pacapt /usr/bin/pacman || true
fi
